package com.wxxymakers.grademark.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wxxymakers.grademark.exception.TipServiceException;
import com.wxxymakers.grademark.model.entity.WxItemPlace;
import com.wxxymakers.grademark.model.mapper.WxItemPlaceMapper;
import com.wxxymakers.grademark.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @AUTHOR soft
 * @DATE 2018/12/29 22:38
 * @DESCRIBE
 */
@Service
public class WxItemPlaceService {

    @Autowired
    private WxItemPlaceMapper placeMapper;

    @Transactional
    public boolean add(WxItemPlace place) {
        if (isExist(place.getItemId(), place.getPlace())) {
            throw new TipServiceException("该人员地位已存在！");
        }
        return placeMapper.insert(place) > 0;
    }

    @Transactional
    public boolean delete(int id) {
        return placeMapper.deleteById(id) > 0;
    }

    @Transactional
    public boolean deleteByIid(int itemId) {
        QueryWrapper<WxItemPlace> wrapper = new QueryWrapper<>();
        wrapper.eq("item_id", itemId);
        try {
            placeMapper.delete(wrapper);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Transactional
    public boolean change(WxItemPlace place) {
        return placeMapper.updateById(place) > 0;
    }

    public WxItemPlace get(int id) {
        return placeMapper.selectById(id);
    }

    /**
     * 根据项目id 和 成员地位判断该记录是不是已存在
     * @param itemId 项目id
     * @param place 成员地位
     */
    public boolean isExist(Integer itemId, Integer place) {
        WxItemPlace itemPlace = new WxItemPlace();
        itemPlace.setItemId(itemId);
        itemPlace.setPlace(place);
        QueryWrapper<WxItemPlace> wrapper = new QueryWrapper<>(itemPlace);
        return placeMapper.selectCount(wrapper) > 0;
    }

    public Page<WxItemPlace> page(int page, int limit, WxItemPlace query) {
        QueryWrapper<WxItemPlace> wrapper = new QueryWrapper<>(query);
        wrapper.orderByDesc("id");

        int total = placeMapper.selectCount(wrapper);
        if (total > 0) {
            List<WxItemPlace> places = placeMapper.selectPage(PageUtils.rowBounds(page, limit), wrapper).getRecords();
            return new PageImpl<>(places, new PageRequest(page - 1, limit), total);
        }
        return null;
    }
}
